package com.jpress.utils;


import java.text.MessageFormat;
import java.util.ResourceBundle;

import javax.el.ELContext;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

public class FacesUtils {
	
	public static final String LOCALE_PATH = "com.jpress.locale.locale_pt";

	public static void addErrorMessage(String id, String msg) {
		FacesMessage fm = new FacesMessage(msg);
		fm.setSeverity(FacesMessage.SEVERITY_ERROR);
		FacesContext.getCurrentInstance().addMessage(id,fm);
	}

	public static void addSucessMessage(String id, String msg) {
		FacesMessage fm = new FacesMessage(msg);
		fm.setSeverity(FacesMessage.SEVERITY_INFO);
		FacesContext.getCurrentInstance().addMessage(id,fm);
	}

	public static void addWarningMessage(String id, String msg) {
		FacesMessage fm = new FacesMessage(msg);
		fm.setSeverity(FacesMessage.SEVERITY_WARN);
		FacesContext.getCurrentInstance().addMessage(id, fm);
	}

	public static void addFatalErrorMessage(String id, String msg) {
		FacesMessage fm = new FacesMessage(msg);
		fm.setSeverity(FacesMessage.SEVERITY_FATAL);
		FacesContext.getCurrentInstance().addMessage(id,fm);
	}

	public static Object getSessionAttribute(String key) {
		return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key);
	}

	public static void setSessionAttribute(String key, Object value) {
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value);
	}

	public static void removeSessionAttribute(String key) {
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(key);
	}

	public static String getRequestAttribute(String key) {
		return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key);
	}

	public static void setRequestAttribute(String key, String value) {
		FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().put(key, value);
	}

	public static void removeRequestAttribute(String key) {
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap().remove(key);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getManagedBean (String name, Class<T> classe){
		ELContext elContext = FacesContext.getCurrentInstance().getELContext();
		return (T)FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, name);
	}

	public static String getMessageBundle(String chave){
		return ResourceBundle.getBundle(LOCALE_PATH, FacesContext.getCurrentInstance().getViewRoot().getLocale()).getString(chave);
	}

	public static String getParamMessageBundle(String chave, Object... valores){
        return MessageFormat.format(ResourceBundle.getBundle(LOCALE_PATH, FacesContext.getCurrentInstance().getViewRoot().getLocale()).getString(chave), valores);
	}
}
